import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:mvvm_provider/page/home/widgets/save.dart';

import '../../../routers/navigator_utils.dart';
import '../../../widgets/easy_loading.dart';

///图片生产水印
class WaterMarkPage extends StatefulWidget {
  //任务ID
  late String imagePath;

  WaterMarkPage({Key? key, required this.imagePath}) : super(key: key);

  @override
  State<WaterMarkPage> createState() => _WaterMarkPageState();
}

class _WaterMarkPageState extends State<WaterMarkPage> {
  GlobalKey _globalKey = GlobalKey();

  String yearStr = '';
  String hourStr = '';
  String weekDayStr = '';

  @override
  void initState() {
    super.initState();
    DateTime now = DateTime.now();
    int year = now.year;
    int month = now.month;
    int day = now.day;
    int hour = now.hour;
    int minute = now.minute;
    int second = now.second;
    print('$year-$month-$day $hour:$minute:$second');
    //声明星期变量
    int weekDay = now.weekday;

    yearStr = '$year-$month-$day';
    hourStr = '${changeTime(hour)}:${changeTime(minute)}';
    weekDayStr = '星期${changeText(weekDay)}';
  }

  String changeText(int time) {
    String str = '';
    List list = [
      '',
      '一',
      '二',
      '三',
      '四',
      '五',
      '六',
      '日',
    ];
    str = list[time];
    return str;
  }

  String changeTime(int time) {
    String str = '';
    if (time < 10) {
      str = '0$time';
    } else {
      str = '$time';
    }
    return str;
  }

  /**
   * 保存签到图片
   */
  Future<void> saveSignImg() async {
    XsEasyLoading.showLoading(message: '保存中');

    ///通过globalkey将Widget保存为ui.Image
    ui.Image _image = await ImageLoaderUtils.imageLoader.getImageFromWidget(_globalKey);

    ui.Image image = _image;
    ByteData? byteData = await (image.toByteData(format: ui.ImageByteFormat.png));
    if (byteData != null) {
      final result = await ImageGallerySaver.saveImage(byteData.buffer.asUint8List(), quality: 100);
      if (result['isSuccess']) {
        XsEasyLoading.dismiss();
        if (mounted) {
          NavigatorUtils.pop(context);
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          "签到图片",
          style: TextStyle(color: Colors.red),
        ),
        elevation: 0,
        leading: const BackButton(
          color: Colors.black,
        ),
        backgroundColor: Colors.transparent,
        centerTitle: true,
        actions: [
          TextButton(
            onPressed: saveSignImg,
            child: const Text('保存'),
          ),
        ],
      ),
      body: Container(
          alignment: Alignment.center,
          child: RepaintBoundary(
            key: _globalKey,
            child: Stack(
              children: [
                Image.file(
                  File(widget.imagePath),
                  width: 1.sw,
                  fit: BoxFit.fitWidth,
                ),
                Container(
                    width: 1.sw,
                    height: 160.h,
                    margin: EdgeInsets.only(top: 500.h),
                    color: Colors.transparent,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(
                          hourStr,
                          style: TextStyle(fontSize: 50.sp, color: Colors.white),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              '$yearStr $weekDayStr ',
                              style: TextStyle(fontSize: 14.sp, color: Colors.white),
                            ),
                            Image(
                              fit: BoxFit.fill,
                              width: 20.w,
                              height: 20.w,
                              image: const AssetImage("assets/images/weizhi.png"),
                            ),
                            Text('北京市富强西里', style: TextStyle(fontSize: 14.sp, color: Colors.white))
                          ],
                        )
                      ],
                    )),
                Positioned(
                    bottom: 20,
                    right: 10,
                    child: Container(
                      child: Row(
                        children: [
                          Image(
                            fit: BoxFit.fill,
                            width: 22.w,
                            height: 22.w,
                            image: const AssetImage("assets/images/shangchuantupian.png"),
                          ),
                          SizedBox(
                            width: 5.w,
                          ),
                          Text('水印相机', style: TextStyle(fontSize: 14.sp, color: Colors.white70))
                        ],
                      ),
                    ))
              ],
            ),
          )),
    );
  }
}
